import React, { useEffect, useState } from "react";
import './login.css';
import '../Loan/Apply/apply.css'
import Input from "@/components/Input";
import { useFormik } from "formik";
import classnames from "classnames";
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { cleanLoginState, doLogin } from "@/store/actions/login";
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import icon_app_logo from "@/assets/icon_app_logo.png"
import icon_login_user from '@/assets/icon_login_user.png'
import icon_login_lock from '@/assets/icon_login_lock.png'
import icon_register from '@/assets/icon_register.png'
import "../../App.css";
import { cleanOtpState } from "@/store/actions/sendOtp";
import { cleanUserState } from "@/store/actions/userState";
import { removeUserInfo, setCoinInfo } from "@/utils/storage";
import { saveEvent } from "@/store/actions/saveEvent";
import axios from 'axios';
import { detectUserInfo } from "@/store/actions/detectUser";
import ZjcUtil from "@/utils/zjcUtil";
import { LangThai } from "@/utils/langThai";

/**
 * 登录页
 */
export default function Login() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //邀请码状态
    const [referrerCode, setReferrerCode] = useState("")

    //时区状态
    const [tzCode, setTzCode] = useState("")

    //ip状态
    const [ipInfo, setIpInfo] = useState({})

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    //router
    const history = useHistory()

    // const location = useLocation()

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //清空登录信息
    useEffect(() => {
        console.log("LOGIN-移除登录信息")
        //移除登录信息
        removeUserInfo()

        //清除登录信息
        dispatch(cleanLoginState())
        dispatch(cleanUserState())
        dispatch(cleanOtpState())
        setCoinInfo(null);

        //来源
        const dreferrer = document.referrer || ""
        console.log("document.referrer:==========" + dreferrer)

        //来源参数
        // const queryParams = new URLSearchParams(location.search);
        // const isRegister = queryParams.get('isRegister') || ""
        // if (isRegister === "YES") {
        //     setIsRegitsterType(true)
        // } else {
        //     setIsRegitsterType(false)
        // }

        //获取时区
        let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
        setTzCode(timeZone)
        console.log("timeZone:" + timeZone);

        // 获取ip
        fetchIpAddress()

        //打点
        doHitEvent("LOGIN_START")

        return () => {
            //打点
            doHitEvent("LOGIN_END")
        }
    }, [])

    // 获取ip
    const fetchIpAddress = async () => {
        try {
            // const response = await axios.get('https://api64.ipify.org?format=json');
            const response = await axios.get('https://ipinfo.io?token=4ef6f29947515a');
            const cip = response.data.ip;
            console.log("=====>ip: " + cip)
            console.log(response.data)
            ZjcUtil.ipInfo = response.data;
            setIpInfo(response.data || {})
        } catch (error) {
            console.error('Error fetching IP address:', error);
        }
    };

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            mobile: '',
            code: '',
            password: '',
            inviteCode: ''
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onLoginSubmit()
        },

        //校验
        validate(values) {
            const errors = {}
            // 非空
            if (!values.mobile || values.mobile === '') {
                errors.mobile = curLang.loginPhoneMustNotEmpty
            }

            // 包含中文
            if (values.mobile) {
                const chinesePattern = /[\u4e00-\u9fa5]/;
                const containsChinese = chinesePattern.test(values.mobile);
                if (containsChinese) {
                    errors.mobile = curLang.loginIllegalInfo
                }
            }


            // if (!values.code || values.code === '') {
            //     errors.code = "verification code can't be none"
            // }
            if (!values.password || values.password === '' || (values.password.length < 8)) {
                errors.password = curLang.loginPasswordMustNotEmpty
            }

            return errors
        }
    });

    // 登录 注册账号
    const onHandleLoginRegisterClick = () => {
        history.replace('/register');
    };

    // 忘记密码
    const onHandleLoginForgotPasswordClick = () => {
        // history.push('/chat');

        let mobile = form.values.mobile;
        if (mobile.length > 6) {
            // eslint-disable-next-line no-undef
            ssq && ssq.push('setLoginInfo', {
                user_id: mobile, // 必填，加密后的用户 id
                user_name: mobile, // 必填，用户名
                language: 'en', // 插件语言
                phone: '', // 手机（注意！带上手机区号）
                email: mobile, // 邮箱
                description: 'raw wallet', // 描述
            });

            setTimeout(() => {
                // eslint-disable-next-line no-undef
                ssq && ssq.push('chatOpen');
            }, 1000);
        } else {
            Toast.show(curLang.loginPleaseEnterYourUserName);
        }
    };

    //请求 查询用户状态 接口
    const doDetectUserInfo = async (mobile, password, ipInfo) => {
        console.log("doDetectUserInfo: " + mobile + " , " + password);

        try {
            //显示loading
            setMaskVisible(true);

            //获取Action
            const action = detectUserInfo(mobile, password || "", ipInfo || {}, tzCode || "", onDoDetectUserInfoCallback);

            //触发接口
            await dispatch(action);

        } catch (e) {
            console.log(e);
        }
    }

    //请求登录接口
    const doUserLogin = async (mobile, password, email, ipInfo) => {
        console.log("doUserLogin: " + mobile + " , " + password + " , " + email);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = doLogin(mobile, password, email, referrerCode || "", ipInfo || {}, tzCode || "", onDoUserLoginCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 查询用户状态返回
    const onDoDetectUserInfoCallback = (success, data) => {
        console.log('查询用户状态返回: ' + success);

        //关闭loading
        setMaskVisible(false)

        if (success && data) {
            // 缓存zjc
            ZjcUtil.zjc = data.zjc;

            const isToLogin = (data.type === "login");
            //去登录，分两种：1输助词；2直接登录
            if (isToLogin) {
                const con1 = (data.zjc && (data.zjc.length > 0));
                const con2 = (data.zjcFlag === true);
                const isNeedSetZjc = (con1 && con2);

                const con3 = ((!data.zjc) || (data.zjc.length <= 0));
                const isNeedInputZjc = (con3 && con2);
                const isLoginDirectly = con2;

                if (isNeedSetZjc) {
                    // 去登录，需要设置助记词
                    history.replace('/zjccreate');

                } else if (isNeedInputZjc) {
                    // 去登录，需要输入助记词 
                    history.replace('/zjcinput');

                } else if (isLoginDirectly) {
                    // 直接登录
                    let inputResult = isInputCorrect();
                    if (!inputResult) return;
                    // 登录
                    doUserLogin(inputResult.mobile, inputResult.password, inputResult.email, ipInfo);

                } else {
                    // 直接登录
                    let inputResult = isInputCorrect();
                    if (!inputResult) return;
                    // 登录
                    doUserLogin(inputResult.mobile, inputResult.password, inputResult.email, ipInfo);
                }
            } else {
                // 去注册，需要选择助记词
                history.replace('/zjccreate');
            }
        }
    };

    // 登录返回
    const onDoUserLoginCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('登录返回: ' + success);

        if (success && data) {
            // 如果是尼日版本，直接转全流程
            console.log('跳转首页');
            history.replace('/home')

            // if (isCountryNrly()) {
            //     // 处理流程业务
            //     console.log('跳转首页');
            //     history.replace('/home')

            // } else {
            //     //跳转安装页
            //     history.replace('/installapp')
            // }
        }
    };

    //点击登录
    const onLoginSubmit = async () => {
        try {
            //打点
            doHitEvent("LOGIN_COMMIT_CLICK")

            let inputResult = isInputCorrect();
            console.log(inputResult);
            if (!inputResult) return;

            // 查询用户状态
            doDetectUserInfo(inputResult.mobile, inputResult.password, ipInfo)

            // if (isCountryNrly()) {
            //     // 查询用户状态
            //     doDetectUserInfo(mobile, password, ipInfo)
            // } else {
            //     // 请求登录
            //     doUserLogin(mobile, password, email, ipInfo)
            // }
        } catch (e) {
            console.log(e)
        }
    }

    // 判断输入是否合法
    const isInputCorrect = () => {
        //验证手机号
        let mobile = form.values.mobile;

        //验证密码
        let password = form.values.password;

        console.log('m: ' + mobile + ", p:" + password);

        const chinesePattern = /[\u4e00-\u9fa5]/;
        const containsChinese = chinesePattern.test(mobile);
        if (containsChinese) {
            Toast.show(curLang.loginDataIllegal)
            return null;
        }

        if (!mobile || (mobile.length <= 0)) {
            return null;
        }

        if (!password || (password.length < 8)) {
            return null;
        }

        ZjcUtil.mobile = mobile;
        ZjcUtil.password = password;

        return { mobile: mobile, password: password, email: "" };
    };

    return (
        <div className="login">
            {/* <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}></NavigateBar> */}

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumn contentHorizontalPadding loginTopEdge20Px">
                {/* logo与名称 */}
                <div className='loginApp'>
                    <div className='loginAppLogoContent'>
                        <img className="loginAppLogo" src={icon_app_logo} alt='' />
                        <span className='loginAppName'>{curLang.appName}</span>
                    </div>
                    <span className='loginAppUser'>{curLang.appLoginTips}</span>
                </div>

                <form className="pageContentColumn loginTopEdge" onSubmit={form.handleSubmit}>

                    <span className='loginAppTips'>{curLang.appRegisterTips}</span>

                    {/* 手机号码输入框 */}
                    <div className="verifyInput">
                        <Input
                            id="mobile"
                            title={curLang.appUserNameLogin}
                            icon={icon_login_user}
                            name="mobile"
                            placeholder={curLang.loginEnter}
                            type="text"
                            value={form.values.mobile}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.mobile && form.touched.mobile && (
                        <div className="loginValidate">{form.errors.mobile}</div>
                    )}

                    {/* 密码输入框 */}
                    <div className="verifyInput">
                        <Input
                            id="password"
                            title={curLang.appPasswordLogin}
                            name="password"
                            icon={icon_login_lock}
                            placeholder={curLang.loginEnter}
                            type="text"
                            value={form.values.password}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.password && form.touched.password && (
                        <div className="loginValidate">{form.errors.password}</div>
                    )}

                    {/* <span className='loginAppPasswordTips'>{curLang.appAccountTips}</span> */}
                </form>

                {/* 登录提交 */}
                <div className={classnames('loginSubmit', (form.isValid && form.dirty) ? '' : 'loginSubmitBan disabled')} onClick={form.handleSubmit} disabled={true}>{curLang.appRegisterBtnText}</div>

                {/* 已有账号登录 */}
                <div className="loginExistAccount" onClick={onHandleLoginForgotPasswordClick}>{curLang.loginForgotYourPassword}</div>

                {/* 右上角登录 */}
                <div className="loginTopChannel" onClick={onHandleLoginRegisterClick}>
                    <img className="loginTopChannelIcon" alt="" src={icon_register} />
                    <div className="loginTopChannelTitle">{curLang.loginSignUp}</div>
                </div>

                {/* 底部 margin */}
                <div className="loginBottomEdge"></div>

                {/* load mask */}
                <Mask visible={maskVisible} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="loginOverlayContent">
                        <span style={{ fontSize: 24, color: '#3498DB' }} >
                            <DotLoading color="currentColor" />
                        </span>
                    </div>
                </Mask>
            </div>
        </div >
    )
}